//
//  ZBShareMenuView.m
//  MessageDisplay
//
//  Created by zhoubin@moshi on 14-5-13.
//  Copyright (c) 2014年 Crius_ZB. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "MessagePhotoView.h"
#import "ZYQAssetPickerController.h"
#import "Library.h"
// 每行有4个
#define kZBMessageShareMenuPerRowItemCount 4
#define kZBMessageShareMenuPerColum 2

#define kZBShareMenuItemIconSize 60
#define KZBShareMenuItemHeight 80

//#define MaxItemCount 5
#define ItemWidth 94
#define ItemHeight 94

@interface MessagePhotoView ()
{
//    UILabel *lblNum;
//    int _iCount;
}

/**
 *  这是背景滚动视图
 */
@property (nonatomic,strong) UIScrollView   *photoScrollView;
@property (nonatomic, weak ) UIScrollView   *shareMenuScrollView;
@property (nonatomic, weak ) UIPageControl  *shareMenuPageControl;
@property (nonatomic,weak  ) UIButton       *btnviewphoto;
@property (nonatomic,strong) NSString       *strDel;
@end

@implementation MessagePhotoView
//@synthesize photoMenuItems;

//- (id)initWithFrame:(CGRect)frame
//{
//    _iCount =0;
//    self = [super initWithFrame:frame];
//    if (self)
//    {
//        [self setup];
//    }
//    return self;
//}
- (void)reloadDataWithImage:(UIImage *)image {
    
}
- (void)reloadData {
    
}

- (id)initWithFrame:(CGRect)frame addPicButton:(NSString *)PicButton
{
//    _iCount =0;
    _addPicButton = PicButton;
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setup:frame];
    }
    
    return self;
}

//- (void)photoItemButtonClicked:(UIButton *)sender
//{
////    if ([self.delegate respondsToSelector:@selector(didSelecteShareMenuItem:atIndex:)])
////    {
//    NSInteger index = sender.tag;
//    if (index < self.photoMenuItems.count)
//    {
//        [self.delegate didSelectePhotoMenuItem:[self.photoMenuItems objectAtIndex:index] atIndex:index];
//    }
////    }
//}

- (void)setup:(CGRect)frame
{
//    self.backgroundColor = [UIColor colorWithRed:248.0f/255 green:248.0f/255 blue:255.0f/255 alpha:1.0];
    self.backgroundColor=[UIColor clearColor];

//    lblNum = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-50, 0, 230, 30)];
    
    _photoScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    _RectImage = CGRectMake(10, frame.size.height/2 - (frame.size.width/2 - 5)*3/4/2, frame.size.width/2 - 5, (frame.size.width/2 - 5)*3/4);
    UIImage *imgBtn = [UIImage imageNamed:_addPicButton];
    _sizeAddPicButton = CGSizeMake(imgBtn.size.width, imgBtn.size.height);
    
//    photoMenuItems = [[NSMutableArray alloc]init];
//    _itemArray = [[NSMutableArray alloc]init];
    _marrImageData = [NSMutableArray new];
    _marrImageAddData = [NSMutableArray new];
    _marrImageNetURL = [NSMutableArray new];
    _marrImageDeleteURL = [NSMutableArray new];
    [self addSubview:_photoScrollView];
    
//    [self addSubview:lblNum];
    
    [self initlizerScrollView:_marrImageData];
}

//-(void)reloadDataWithImage:(UIImage *)image
//{
//    [self.photoMenuItems addObject:image];
//    
//    [self initlizerScrollView:self.photoMenuItems];
//}
- (void)setSizeAddPicButton:(CGSize)sizeAddPicButton
{
    _sizeAddPicButton = sizeAddPicButton;
    [self initlizerScrollView:_marrImageData];
}

/**
 *  设置图片大小
 *
 *  @param RectImage
 */
- (void)setRectImage:(CGRect)RectImage
{
    _RectImage = RectImage;
    [self initlizerScrollView:_marrImageData];
}

/**
 *  设置图片上限
 *
 *  @param iMaxItemCount
 */
- (void)setIMaxItemCount:(NSInteger)iMaxItemCount
{
    _iMaxItemCount = iMaxItemCount;
    [self initlizerScrollView:_marrImageData];
}

/**
 *  设置初始网络图片
 *
 *  @param marrImageNetURL
 */
- (void)setMarrImageNetURL:(NSMutableArray *)marrImageNetURL
{
    _marrImageNetURL = marrImageNetURL;
    [_marrImageData removeAllObjects];
    if (_marrImageNetURL.count == 0)
    {
        [self initlizerScrollView:_marrImageData];
        return;
    }
    
    dispatch_queue_t queue = dispatch_queue_create("333", nil);
    
    dispatch_async(queue, ^{
        NSData *dataImg ;
        for (int i = 0; i < marrImageNetURL.count; i++)
        {
            dataImg = [NSData dataWithContentsOfURL:[NSURL URLWithString:marrImageNetURL[i]]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [_marrImageData addObject:dataImg];
                [self initlizerScrollView:_marrImageData];
            });
        }
    });
}

/**
 *  根据marrImageData重画页面
 *
 *  @param marrImageData 图片数据
 */
-(void)initlizerScrollView:(NSArray *)marrImageData
{
    NSMutableArray *marr = [self.photoScrollView.subviews mutableCopy];
    for (int i = 0;i < marr.count;i++)
    {
        if (![marr[i] isKindOfClass:[MessagePhotoMenuItem class]]&&![marr[i] isKindOfClass:[UIButton class]])
        {
            [marr removeObject:marr[i]];
            i--;
        }
    }
    [marr makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for(int i=0;i<marrImageData.count;i++)
    {
        MessagePhotoMenuItem *photoItem = [[MessagePhotoMenuItem alloc]initWithFrame:CGRectMake(i * (_RectImage.size.width + _RectImage.origin.x), _RectImage.origin.y, _RectImage.size.width, _RectImage.size.height)];
        photoItem.delegate = self;
        photoItem.index = i;
        photoItem.contentImage = [UIImage imageWithData:marrImageData[i]];
        [self.photoScrollView addSubview:photoItem];
    }
    
    
    if(!_iMaxItemCount || marrImageData.count < _iMaxItemCount)
    {
        UIButton *btnphoto=[UIButton buttonWithType:UIButtonTypeCustom];
        
        //根据图片大小设置按钮大小
        [btnphoto setFrame:CGRectMake(marrImageData.count*(_RectImage.size.width + _RectImage.origin.x), (_RectImage.size.height  - _sizeAddPicButton.height)/2 + _RectImage.origin.y, _sizeAddPicButton.width, _sizeAddPicButton.height)];
        [btnphoto setBackgroundImage:[UIImage imageNamed:_addPicButton] forState:UIControlStateNormal];
        //给添加按钮加点击事件
        [btnphoto addTarget:self action:@selector(openMenu) forControlEvents:UIControlEventTouchUpInside];
        [self.photoScrollView addSubview:btnphoto];
        [self.photoScrollView setContentSize:CGSizeMake(btnphoto.frame.size.width + (_RectImage.size.width + 10) * marrImageData.count, 0)];
        if (self.photoScrollView.contentSize.width - self.photoScrollView.width > 0)
        {
             [self.photoScrollView setContentOffset:CGPointMake(self.photoScrollView.contentSize.width - self.photoScrollView.width, 0)];
        }
    }
    else
    {
        [self.photoScrollView setContentSize:CGSizeMake((_RectImage.size.width + 10) * marrImageData.count - 5, 0)];
    }
}

- (void)TackPhoto:(NSData *)ImageData
{
    //拍照返回
    if ([_strDel isEqualToString:@"not"])
    {
        [_marrImageData addObject:ImageData];
        [_marrImageAddData addObject:ImageData];
    }
    [self initlizerScrollView:_marrImageData];
}

-(void)openMenu
{
    //在这里呼出下方菜单按钮项
//    myActionSheet = [[UIActionSheet alloc]
//                     initWithTitle:nil
//                     delegate:self
//                     cancelButtonTitle:@"取消"
//                     destructiveButtonTitle:nil
//                     otherButtonTitles:@"打开照相机",@"从手机相册获取", nil];
    myActionSheet = [[CCActionSheet alloc] initWithTitle:nil
                                                delegate:self
                                       cancelButtonTitle:@"取消"
                                       otherButtonTitles:@"打开照相机",@"从手机相册获取", nil];
    //刚才少写了这一句
    [myActionSheet show];
//    [myActionSheet showInView:self.window];
}

//下拉菜单的点击响应事件
- (void)actionSheet:(CCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    switch (buttonIndex)
    {
        case 0:
            //            if (_marrImage.count == 6)
            //            {
            //                [SVProgressHUD showErrorWithStatus:@"选择照片超过上限！"];
            //            }
            //            else
        {
            [self takePhoto];
        }
            break;
        case 1:
            [self localPhoto];
            break;
        default:
            break;
    }

}

//-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//}

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = sourceType;
        picker.allowsEditing = YES;
        [self.delegate addUIImagePicker:picker];
    }
    else
    {
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"本设备不支持该功能" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSString *strType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([strType isEqualToString:@"public.image"]) //当选择的类型是图片
    {
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; //先把图片转成NSData
        image = [self fixOrientation:image];
        [picker dismissViewControllerAnimated:YES completion:nil]; //关闭相册界面
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.01);
//        _iCount++;
        _strDel = @"not";
        [self TackPhoto:imageData];
    }
}
// 新增的旋转解决方案
///////////////////////////////////////////////////////////////////////////////////////
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
///////////////////////////////////////////////////////////////////////////////////////
/*
    新加的另外的方法
 */
////////////////////////////////////////////////////////////
//打开相册，可以多选
-(void)localPhoto
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc]init];
    
    picker.maximumNumberOfSelection = (_iMaxItemCount)?_iMaxItemCount - self.marrImageData.count:100;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings)
    {
        if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypeVideo])
        {
            NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
            return duration >= 5;
        }
        else
        {
            return  YES;
        }
    }];
    
    [self.delegate addPicker:picker];
}

#pragma  mark   -ZYQAssetPickerController Delegate

/*
 得到选中的图片
 */
#pragma mark - ZYQAssetPickerController Delegate

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    for (int i = 0; i < assets.count; i++)
    {
        ALAsset *asset=assets[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        NSData *datas = UIImageJPEGRepresentation(tempImg, 0.5);
        [self.marrImageData addObject:datas];
        [_marrImageAddData addObject:datas];
    }

    [self initlizerScrollView:self.marrImageData];
    [SVProgressHUD dismiss];
}

#pragma mark - MessagePhotoItemDelegate
//删除图片
-(void)messagePhotoItemView:(MessagePhotoMenuItem *)messagePhotoItemView didSelectDeleteButtonAtIndex:(NSInteger)index
{
    [self.marrImageData removeObjectAtIndex:index];
    if (index < _marrImageNetURL.count)
    {
        [_marrImageDeleteURL addObject:[_marrImageNetURL objectAtIndex:index]];
        [_marrImageNetURL removeObjectAtIndex:index];
    }
    else
    {
        [_marrImageAddData removeObjectAtIndex:index - _marrImageNetURL.count];
    }
    _strDel = @"yes";
    [self TackPhoto:nil];
}

#pragma mark - MessagePhotoItemDelegate
//点击图片
- (void)messagePhotoItem:(MessagePhotoMenuItem *)messagePhotoItemView didSelectPhotoItemAtIndex:(NSInteger)index
{

    if([self.delegate respondsToSelector:@selector(messagePhotoView:didSelectPhotoItemAtIndex:)])
    {
        [self.delegate messagePhotoView:messagePhotoItemView
                  didSelectPhotoItemAtIndex:index];
    }
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //每页宽度
    CGFloat pageWidth = scrollView.frame.size.width;
    //根据当前的坐标与页宽计算当前页码
    NSInteger currentPage = floor((scrollView.contentOffset.x - pageWidth/2)/pageWidth)+1;
    [self.shareMenuPageControl setCurrentPage:currentPage];
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
